package cn.com.dstz.image;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import cn.com.dstz.utils.Common;



/**
 * 图片辅助类
 * 
 * 
 */
public abstract class ImageUtils {
	
	private static final boolean USE_TRANSFORM = false;
	
	/**
	 * 图片的后缀
	 */
	public static final String[] IMAGE_EXT = new String[] { "jpg", "jpeg","gif", "png", "bmp" };

	/**
	 * 是否是图片
	 * 
	 * @param ext
	 * @return "jpg", "jpeg", "gif", "png", "bmp" 为文件后缀名者为图片
	 */
	public static boolean isValidImageExt(String ext) {
		ext = ext.toLowerCase(Locale.ENGLISH);
		for (String s : IMAGE_EXT) {
			if (s.equalsIgnoreCase(ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Checks if the underlying input stream contains an image.
	 * 
	 * @param in
	 *            input stream of an image
	 * @return <code>true</code> if the underlying input stream contains an
	 *         image, else <code>false</code>
	 */
	public static boolean isImage(final InputStream in) {
		ImageInfo ii = new ImageInfo();
		ii.setInput(in);
		return ii.check();
	}

	/**
	 * 获得水印位置
	 * 
	 * @param width
	 *            原图宽度
	 * @param height
	 *            原图高度
	 * @param p
	 *            水印位置 1-5，其他值为随机。1：左上；2：右上；3：左下；4：右下；5：中央。
	 * @param offsetx
	 *            水平偏移。
	 * @param offsety
	 *            垂直偏移。
	 * @return 水印位置
	 */
	public static Position markPosition(int width, int height, int p,
			int offsetx, int offsety) {
		if (p < 1 || p > 5) {
			p = (int) (Math.random() * 5) + 1;
		}
		int x, y;
		switch (p) {
		// 左上
		case 1:
			x = offsetx;
			y = offsety;
			break;
		// 右上
		case 2:
			x = width + offsetx;
			y = offsety;
			break;
		// 左下
		case 3:
			x = offsetx;
			y = height + offsety;
			break;
		// 右下
		case 4:
			x = width + offsetx;
			y = height + offsety;
			break;
		// 中央
		case 5:
			x = (width / 2) + offsetx;
			y = (height / 2) + offsety;
			break;
		default:
			throw new RuntimeException("never reach ...");
		}
		return new Position(x, y);
	}

	/**
	 * 水印位置
	 * 
	 * 包含左边偏移量，右边偏移量。
	 * 
	 */
	public static class Position {
		private int x;
		private int y;

		public Position(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int getX() {
			return x;
		}

		public void setX(int x) {
			this.x = x;
		}

		public int getY() {
			return y;
		}

		public void setY(int y) {
			this.y = y;
		}
	}
	
	/**
	 * 判断图片的宽高是否大于指定宽高
	 * @param srcImgPath
	 * @param width
	 * @param height
	 * @return
	 
	public static boolean isMax( String srcImgPath, int width, int height ){
		return isMax( new File(  srcImgPath ), width, height );
	}
	
	public static boolean isMax( File srcFile, int width, int height ){
		
		if( srcFile == null ){
			return false;
		}
		
		try {
			BufferedImage srcImg = ImageIO.read(srcFile);
			
			float src_w = srcImg.getWidth();
			float src_h = srcImg.getHeight();
			
			if( src_w >= width && src_h >= height ){
				return true;
			}
			
		} catch ( IOException e ) {
			e.printStackTrace();
		}
		
		return false;
		
		
	}
	*/
	
	
	
	public static String makeThumb( String rootPath, File srcFile, int tow, int toh, int maxtow, int maxtoh ){
		
		if (!srcFile.exists()) {
			return null;
		}
		
		String thumbPath = srcFile.getName ( ) + ".thumb.jpg";
		
		String destPath = rootPath + File.separator + thumbPath;
		
		File destFile = new File(destPath);
		if (tow < 60) {
			tow = 60;
		}
		if (toh < 60) {
			toh = 60;
		}
		boolean make_max = false;
		if (maxtow >= 300 && maxtoh >= 300) {
			make_max = true;
		}
		String srcImgType = Common.getImageType(srcFile);
		if ("gif".equals(srcImgType)) {
			make_max = false; 
		}
		try {
			BufferedImage srcImg = ImageIO.read(srcFile);
			float src_w = srcImg.getWidth();
			float src_h = srcImg.getHeight();
			if (src_w <= maxtow && src_h <= maxtoh){
				make_max = false;
			}
			float thumb_ratio = tow / toh; 
			float src_ratio = src_w / src_h; 
			if (thumb_ratio <= src_ratio) {
				toh = (int) (tow / src_ratio);
				maxtoh = (int) (maxtow * (src_h / src_w));
			} else {
				tow = (int) (toh * src_ratio);
				maxtow = (int) (maxtoh * (src_w / src_h));
			}
			if (src_w > tow || src_h > toh) {
				double x_ratio = (double) tow / src_w; 
				double y_ratio = (double) toh / src_h; 
				AffineTransform tx = new AffineTransform();
				tx.setToScale(x_ratio, y_ratio);
				BufferedImage thumbImg = new BufferedImage(tow, toh, BufferedImage.TYPE_3BYTE_BGR);
				Graphics2D g2d = thumbImg.createGraphics();
				if (USE_TRANSFORM) {
					g2d.drawImage(srcImg, tx, null);
				} else {
					Image scaleImg = getScaledInstance(srcImg, tow, toh);
					g2d.drawImage(scaleImg, 0, 0, null);
				}
				g2d.dispose();
				ImageIO.write(thumbImg, "jpeg", destFile);
				if (make_max) {
					BufferedImage maxImg = new BufferedImage(maxtow, maxtoh, BufferedImage.TYPE_3BYTE_BGR);
					g2d = maxImg.createGraphics();
					if (USE_TRANSFORM) {
						g2d.drawImage(srcImg, tx, null);
					} else {
						Image scaleImg = getScaledInstance(srcImg, maxtow, maxtoh);
						g2d.drawImage(scaleImg, 0, 0, null);
					}
					g2d.dispose();
					ImageIO.write(maxImg, "jpeg", srcFile);
				}
			}
		} catch (IOException e) {
			return null;
		}
		return destFile.exists() ? thumbPath : null;
		
	}
	
	/**
	 * @param srcImgPath
	 * @param tow  宽
	 * @param toh  高
	 * @param maxtow  最大宽
	 * @param maxtoh  最大高
	 * @return
	 */
	public static String makeThumb( String rootPath, String srcImgPath, int tow, int toh, int maxtow, int maxtoh ) {
		File srcFile = new File( rootPath + File.separator + srcImgPath);
		if (!srcFile.exists()) {
			return null;
		}
		
		String thumbPath =  File.separator + srcImgPath + ".thumb.jpg";
		
		String destPath =  rootPath +thumbPath;
		File destFile = new File(destPath);
		if (tow < 60) {
			tow = 60;
		}
		if (toh < 60) {
			toh = 60;
		}
		boolean make_max = false;
		if (maxtow >= 300 && maxtoh >= 300) {
			make_max = true;
		}
		String srcImgType = Common.getImageType(srcFile);
		if ("gif".equals(srcImgType)) {
			make_max = false; 
		}
		try {
			BufferedImage srcImg = ImageIO.read(srcFile);
			float src_w = srcImg.getWidth();
			float src_h = srcImg.getHeight();
			if (src_w <= maxtow && src_h <= maxtoh){
				make_max = false;
			}
			float thumb_ratio = tow / toh; 
			float src_ratio = src_w / src_h; 
			if (thumb_ratio <= src_ratio) {
				toh = (int) (tow / src_ratio);
				maxtoh = (int) (maxtow * (src_h / src_w));
			} else {
				tow = (int) (toh * src_ratio);
				maxtow = (int) (maxtoh * (src_w / src_h));
			}
			if (src_w > tow || src_h > toh) {
				double x_ratio = (double) tow / src_w; 
				double y_ratio = (double) toh / src_h; 
				AffineTransform tx = new AffineTransform();
				tx.setToScale(x_ratio, y_ratio);
				BufferedImage thumbImg = new BufferedImage(tow, toh, BufferedImage.TYPE_3BYTE_BGR);
				Graphics2D g2d = thumbImg.createGraphics();
				if (USE_TRANSFORM) {
					g2d.drawImage(srcImg, tx, null);
				} else {
					Image scaleImg = getScaledInstance(srcImg, tow, toh);
					g2d.drawImage(scaleImg, 0, 0, null);
				}
				g2d.dispose();
				ImageIO.write(thumbImg, "jpeg", destFile);
				if (make_max) {
					BufferedImage maxImg = new BufferedImage(maxtow, maxtoh, BufferedImage.TYPE_3BYTE_BGR);
					g2d = maxImg.createGraphics();
					if (USE_TRANSFORM) {
						g2d.drawImage(srcImg, tx, null);
					} else {
						Image scaleImg = getScaledInstance(srcImg, maxtow, maxtoh);
						g2d.drawImage(scaleImg, 0, 0, null);
					}
					g2d.dispose();
					ImageIO.write(maxImg, "jpeg", srcFile);
				}
			}
		} catch (IOException e) {
			return null;
		}
		return destFile.exists() ? thumbPath : null;
	}
	
	private static Image getScaledInstance(BufferedImage srcImage, int imageWidth, int imageHeight) {
		ImageFilter filter = new java.awt.image.AreaAveragingScaleFilter(imageWidth, imageHeight);
		ImageProducer prod = new FilteredImageSource(srcImage.getSource(), filter);
		Image newImage = Toolkit.getDefaultToolkit().createImage(prod);
		ImageIcon imageIcon = new ImageIcon(newImage);
		Image scaleImg = imageIcon.getImage();
		return scaleImg;
	}
	
	

}
